#include <bits/stdc++.h>
using namespace std;

#define S64_t long long
#define U64_t unsigned long long
char stk[10000];
int top;
 

bool judge(char c){
   if(top<=0) return false;
   if (stk[--top] != c) return  false;       
   return true;
}

bool judge2(char cOut)
{
   char mch[][3]={"<>","()", "[]", "{}"};
   if (top <= 0) return false;
   for(int i=0; i<4; i++){
      if(cOut == mch[i][1]){
         return stk[--top] == mch[i][0];
      }
   }
   return false;
}

bool judgeLine(string s)
{
   top = 0;
   bool isOk = true;
   char ch, ch2;
   if(s.length() < 2) return false;
   for (int i = 0; i < s.length(); i++)
   {
      ch = s[i];
      if ('<' == ch || '(' == ch || '[' == ch || '{' == ch) stk[top++] = ch;
      if ('>' == ch || ')' == ch || ']' == ch || '}' == ch)
      {
         isOk = judge2(ch);
         if(top>0){
            ch2 = stk[top - 1];         
            if (')' == ch && ('<' == ch2)) isOk = false;
            if (']' == ch && ('<' == ch2 || '(' == ch2) )isOk = false;
            if ('}' == ch && ('<' == ch2 || '(' == ch2 || '[' == ch2) ) isOk = false;
         }
         if(i < s.length() - 1){
            ch2 = s[i+1];
            if (')' == ch && ('>' == ch2)) isOk = false;
            if (']' == ch && ('>' == ch2 || ')' == ch2) )isOk = false;
            if ('}' == ch && ('>' == ch2 || ')' == ch2 || ']' == ch2) ) isOk = false;
         }
         if (!isOk) break;
      }
   }

   return isOk && top == 0;
}

int main()
{
   string s;
   int n;
   char ch;
   cin >> n;
   bool isOk = true;
   for(int i=0; i<n; i++) 
   {
      cin >> s;
      printf("%s\n", judgeLine(s) ? "YES" : "NO");
   }

   return 0;
}
/*
5
{}{}<><>()()[][]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{{}}{{}}<<>><<>>(())(())[[]][[]]
{<>}{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]
><}{{[]}<<<>><<>>>((<>))(())[[(<>)]][[]]

YES
YES
YES
YES
NO


5
}}}}}}{{{{{{<<<<<<>>>>>>))))))(((((())))))(((((([[[[[[]]]]]]
[[[[[[[[[[]]]]]]]]]{{{{{{{{{}}}}}}}}}]
<<<<>>>>((((<<>>)<>)<>)<>)
<<<<(())>()>()>()>
{{{{{{{{{{[[[[[[[[[[((((((((((<<<<<<<<<<>>>>>>>>>>))))))))))]]]]]]]]]]}}}}}}}}}}

NO
NO
YES
NO
YES
*/